package middlewares

/*
 +----------------------------------------------------------------------
 + Title        : FuseMiddleware
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2021-09-22
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 熔断中间件
 +----------------------------------------------------------------------
*/
import (
	"fmt"
	"time"

	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/base"
	"github.com/gin-gonic/gin"
)

func FuseMiddleware(ctx *gin.Context) {
	e, b := sentinel.Entry("request-circuitbreaker", sentinel.WithResourceType(base.ResTypeWeb), sentinel.WithTrafficType(base.Inbound))
	if b != nil {
		ctx.JSON(200, gin.H{
			"code":    200,
			"message": "静态数据",
			"data":    nil,
		})

		// 终止程序
		ctx.Abort()
		return
	} else {
		defer e.Exit() // 不要忘了加它
		if time.Now().Unix()%2 == 0 {
			sentinel.TraceError(e, fmt.Errorf("sentinel TraceError"))
			ctx.JSON(500, gin.H{
				"code":    500,
				"message": "异常",
				"data":    nil,
			})
			// 终止程序
			ctx.Abort()
			return
		}
	}

	ctx.Next()
}
